package net.pulseproject.router.config.instantiator.builder;

import net.pulseproject.commons.midi.entity.MidiSocket;
import net.pulseproject.router.config.instantiator.builder.validator.FieldValidator;
import net.pulseproject.router.config.instantiator.builder.validator.SkeletonFieldValidator;
import net.pulseproject.router.modules.MidiModule;


public abstract class MidiModuleBuilder<T extends MidiModule> extends Builder<T> {

	private String port;
	
	private Integer channel;

	private Integer controller = MidiSocket.IGNORE_CONTROLLER;

	
	private final FieldValidator validator = new SkeletonFieldValidator() {
		@Override
		protected void validateFields() {
			if(MidiModuleBuilder.this.getPort() == null) {
				throw new RuntimeException("port not yet set");
			}
			if(MidiModuleBuilder.this.getChannel() == null) {
				throw new RuntimeException("channel not yet set");
			}
			if(MidiModuleBuilder.this.getController() == null) {
				throw new RuntimeException("controller not yet set");
			}
		}
	};
	
	
	public MidiModuleBuilder() {
		this.addValidator(this.validator);
	}
	
	protected final String getPort() {
		return this.port;
	}
	
	public final void setPort(final String port) {
		this.port = port;
	}

	protected final Integer getChannel() {
		return this.channel;
	}
	
	public final void setChannel(final Integer channel) {
		this.channel = Integer.valueOf(channel.intValue() - 1); // convert from 1-based to 0-based indexed
	}

	protected final Integer getController() {
		if(this.controller == null) {
			return null;
		}
		if(this.controller.equals(MidiSocket.IGNORE_CONTROLLER)) {
			return this.controller;
		}
		
		return Integer.valueOf(this.controller.intValue()); // TODO really not convert from 1-based to 0-based indexed?!
	}
	
	public final void setController(final Integer controller) {
		this.controller = controller;
	}

}
